import {Component} from '@angular/core';
import {ArticleFavoriteService} from "../../../service/article/article.favorite.service";
import {NavController, ToastController} from "ionic-angular";
import {ArticlePage} from "../article";


@Component({
  selector: 'page-article-favorite',
  templateUrl: 'favorite.html',
  providers: [ArticleFavoriteService]
})
export class ArticleFavoritePage {
  private articles: any;

  private loadOver: boolean = false;

  private params: any = {page: 0, size: 10};

  constructor(private  articleFavoriteService: ArticleFavoriteService,
              private toast: ToastController,
              private navController: NavController) {

  }

  ionViewDidLoad() {
    this.queryFavorite(null);
  }

  loadMore(infiniteScroll: any) {
    if (this.loadOver) {
      infiniteScroll.complete();
      return;
    }
    this.params.page += 1;
    this.queryFavorite(infiniteScroll);
  }

  queryFavorite(infiniteScroll: any) {
    this.articleFavoriteService.query(this.params).subscribe(res => {
      if (res.status === "SUCCESS") {
        if (res.data.content.length < this.params.size) {
          this.loadOver = true;
        }
        if (this.articles) {
          for (let v in res.data.content){
            this.articles.push(res.data.content[v]);
          }
          // this.articles = this.articles.push(res.data.content)
        } else {
          this.articles = res.data.content;
        }
        if (infiniteScroll)
          infiniteScroll.complete();
      } else {
        this.toast.create({
          message: res.message,
          duration: 2000,
          position: 'top'
        }).present();
        if (infiniteScroll)
          infiniteScroll.complete();
      }
    })
  }

  articleDetailClick(article: any) {
    this.navController.push(ArticlePage, {article: article});
  }
}
